<template>
  <div>
    <h1>品牌管理案例</h1>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>资产名称</th>
          <th>价格</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- // 1：循环渲染数据 -->
        <tr v-for="item in arr"
            :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>{{item.time}}</td>
          <td><a href="
            javascript:;"
               @click="del(item.id)">删除</a></td>
        </tr>
      </tbody>
    </table>
    <input type="text"
           placeholder="资产名称"
           v-model.trim="Sname">
    <input type="text"
           placeholder="资产价格"
           v-model="Sprice">
    <button @click="add">添加一件商品</button>
  </div>
</template>

<script>
// 3个功能： 
export default {
  data () {
    return {
      arr: [
        {
          id: 1,
          name: '衣服',
          price: 188,
          time: '2021-11-11',
        },
        {
          id: 2,
          name: '鞋子',
          price: 198,
          time: '2021-11-21',
        },
        {
          id: 3,
          name: '帽子',
          price: 128,
          time: '2021-11-1',
        }
      ],
      Sname: '',
      Sprice: 0

    }
  },
  methods: {
    // 2：点击添加一条数据
    add () {
      if (this.Sname.length <= 0 || this.Sprice === 0) {
        alert('请输入商品名称和价格')
        return
      }
      let id = this.arr.length > 0 ? this.arr.length + 1 : 100;
      this.arr.push({
        id: id,
        name: this.Sname,
        price: this.Sprice,
        time: new Date()
      })
      this.Sname = '',
        this.Sprice = 0
    },
    // 3：点击删除一条数据
    del (idx) {
      // 	1:先找到id
      let id = this.arr.findIndex(item => item.id === idx)
      // 2: 使用splice根据id删除
      this.arr.splice(id, 1)
    }
  },
}
</script>

<style scoped>
table {
  /* border: 1px solid red; */
  width: 500px;
  text-align: center;
  padding: 0px;
  border-spacing: 0px;
}
thead {
  background-color: #ccc;
}
tbody tr td {
  border-collapse: collapse;
  border: 1px solid blue;
}
</style>